package com.neusoft.databus.core.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.exception.CustomRuntimeException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.databus.common.dto.GatewayDTO;
import com.neusoft.databus.core.service.GatewayService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 网关管理控制器
 *
 * @author sunchf
 * @date 2019年1月17日 下午2:16:41
 */
@Slf4j
@Api("网关管理控制器")
@RestController
@RequestMapping(value = "/api/w/gateways")
public class GatewayController {

    @Autowired
    private GatewayService gatewayService;

    /**
     * 查询所有网关 <br>
     * GET <br>
     *
     * @return ResultListDTO
     */
    @ApiOperation("查询所有网关")
    @GetMapping
    public ResultListDTO<GatewayDTO> index(final Searchable searchable) {
        final List<GatewayDTO> DTOs = this.gatewayService.search(searchable);
        final ResultListDTO<GatewayDTO> result = ResultListDTO.success(DTOs);
        return result;
    }

    @ApiOperation("分页查询所有网关")
    @GetMapping("/p")
    public PageResultDTO<GatewayDTO> search(final Searchable searchable, final Pageable pageable) {
        final Page<GatewayDTO> DTOs = this.gatewayService.search(pageable, searchable);
        return PageResultDTO.success(DTOs);
    }

    /**
     * 网关详情 <br>
     * GET <br>
     *
     * @param dto GatewayDTO
     * @return ResultDTO<GatewayDTO>
     */
    @ApiOperation("网关详情")
    @GetMapping("/{code}")
    public ResultDTO<GatewayDTO> get(@PathVariable final String code) {
        final GatewayDTO gateway = this.gatewayService.findByCodeWithResources(code);
        return ResultDTO.success(gateway);
    }

    /**
     * 创建网关 <br>
     * POST <br>
     *
     * @param dto GatewayDTO
     * @return ResultDTO<GatewayDTO>
     */
    @ApiOperation("创建网关")
    @PostMapping
    public ResultDTO<GatewayDTO> create(@RequestBody final GatewayDTO dto) {
        final GatewayDTO result = this.gatewayService.create(dto);
        return ResultDTO.success(result);
    }

    /**
     * 删除网关，物理删除 <br>
     * DELETE <br>
     *
     * @param code 网关编码
     * @return ResultDTO<Void>
     * @throws CustomRuntimeException
     */
    @ApiOperation("删除网关，物理删除")
    @DeleteMapping("/{code}")
    public ResultDTO<Void> delete(@PathVariable final String code) {
        this.gatewayService.delete(code);
        return ResultDTO.success();
    }

    /**
     * 更新网关，仅更新网关的基本属性
     *
     * @param code 网关编码
     * @param dto 网关DTO
     * @return ResultDTO<GatewayDTO>
     * @throws CustomRuntimeException
     */
    @ApiOperation(value = "更新网关", notes = "仅更新网关的基本属性")
    @PutMapping("/{code}")
    public ResultDTO<GatewayDTO> update(@PathVariable final String code, @RequestBody final GatewayDTO dto) {
        final GatewayDTO result = this.gatewayService.update(code, dto);
        return ResultDTO.success(result);
    }

    /**
     * 启用网关
     *
     * @param code 网关编码
     * @return ResultDTO<Void>
     * @throws CustomRuntimeException
     */
    @ApiOperation("启用网关")
    @PutMapping("/{code}/enable")
    public ResultDTO<Void> enable(@PathVariable final String code) {
        this.gatewayService.enable(code);
        return ResultDTO.success();
    }

    /**
     * 禁用网关
     *
     * @param code 网关编码
     * @return ResultDTO<Void>
     * @throws CustomRuntimeException
     */
    @ApiOperation(" 禁用网关")
    @PutMapping("/{code}/disable")
    public ResultDTO<Void> disable(@PathVariable final String code) {
        this.gatewayService.disable(code);
        return ResultDTO.success();
    }

    /**
     * 网关导入
     *
     * @param file
     * @return
     */
    @ApiOperation("网关导入")
    @PostMapping("/import")
    public ResultDTO<?> importTpl(@RequestParam("file") final MultipartFile file) {
        this.gatewayService.importTpl(file);
        return ResultDTO.success();
    }

    /**
     * 网关导出
     *
     * @param file
     * @return
     */
    @ApiOperation("网关导出")
    @GetMapping("/export")
    public void export(final Searchable searchable, final Pageable pageable, final HttpServletResponse response) {
        this.gatewayService.export(searchable, pageable, response);
    }

    @ApiOperation("下载网关导入模版")
    @GetMapping("/template")
    public void downloadTpl(final HttpServletResponse response) {

        final SXSSFWorkbook workbook = this.gatewayService.getTpl();
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode(workbook.getSheetName(0) + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            GatewayController.log.error("", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                GatewayController.log.error("", e);
            }
        }

    }

    /**
     * 启用网关批处理
     *
     * @param code 网关编码
     * @return ResultDTO<Void>
     * @throws CustomRuntimeException
     */
    @ApiOperation("启用网关批处理")
    @PutMapping("/{code}/batch/enable")
    public ResultDTO<Void> enableBatch(@PathVariable final String code) {
        this.gatewayService.batch(code, true);
        return ResultDTO.success();
    }

    /**
     * 禁用网关批处理
     *
     * @param code 网关编码
     * @return ResultDTO<Void>
     * @throws CustomRuntimeException
     */
    @ApiOperation(" 禁用网关批处理")
    @PutMapping("/{code}/batch/disable")
    public ResultDTO<Void> disableBatch(@PathVariable final String code) {
        this.gatewayService.batch(code, false);
        return ResultDTO.success();
    }
}
